package com.lai.note.fragment;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.DateFormat;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.lai.note.R;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;


public class IndexFragment extends Fragment {

    public IndexFragment(){
        super(R.layout.fragment_index);
    }

    private TextView tv_time;

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        tv_time = getView().findViewById(R.id.tv_time);
        new TimeThread().start();//开启线程
    }

    class TimeThread extends Thread{
        @Override
        public void run() {
            do{
                try{
                    Thread.sleep(1000);
                    Message msg = new Message();
                    msg.what = 1;
                    mHandler.sendMessage(msg);//每隔一秒发送一个msg给mhandler
                }catch(InterruptedException e){
                    e.printStackTrace();
                }
            }while (true);
        }
    }

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch(msg.what){
                case 1:
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
                    //获取当前日期
                    Date date = new Date(System.currentTimeMillis());
                    tv_time.setText(simpleDateFormat.format(date) +"  "+ getWeek());
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 根据当前日期获得是星期几
     * time=yyyy-MM-dd
     * @return
     */
    public static String getWeek() {
        String Week = "";
        Calendar c = Calendar.getInstance();

        int wek=c.get(Calendar.DAY_OF_WEEK);

        if (wek == 1) {
            Week += "星期日";
        }
        if (wek == 2) {
            Week += "星期一";
        }
        if (wek == 3) {
            Week += "星期二";
        }
        if (wek == 4) {
            Week += "星期三";
        }
        if (wek == 5) {
            Week += "星期四";
        }
        if (wek == 6) {
            Week += "星期五";
        }
        if (wek == 7) {
            Week += "星期六";
        }
        return Week;
    }
}
